package se.nikmel.AnDisper.DisperServer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import se.nikmel.AnDisper.MainActivity;
import se.nikmel.AnDisper.Application.Application;
import android.net.Uri;
import android.util.Log;

public class IconCache {
	private final static String TAG = "IconCache";
	private MainActivity m_actParent;

	public IconCache(MainActivity p_actParent) {
		m_actParent = p_actParent;
	}

	/**
	 * Saves the provided icon to the cache. The provided MD5 digest will be
	 * used as filename
	 * 
	 * @param p_bteData
	 * @param p_sMD5
	 */
	private File saveIcon(byte[] p_bteData, String p_sMD5) {
		File fleCacheDir = m_actParent.getCacheDir();

		try {
			File fleIcon = new File(fleCacheDir, p_sMD5 + ".icon");
			FileOutputStream outIcon = new FileOutputStream(fleIcon);
			outIcon.write(p_bteData);
			outIcon.flush();
			outIcon.close();
			Log.v(TAG, "(II) Saved icon: " + fleIcon.getAbsolutePath());
			return fleIcon;

		} catch (IOException e) {
			Log.e(TAG, "(EE) Failed to create temp-file with new icon!", e);
			return null;
		}
	}

	public Uri getIconURI(String p_sAppID, String p_sMD5) {
		// 1. Check if cache-dir contains the file
		File fleIcon = new File(m_actParent.getCacheDir(), p_sMD5 + ".icon");

		if (fleIcon.exists()) {
			Log.v(TAG,
					"(II) Using cached version of icon: "
							+ fleIcon.getAbsolutePath());
			return Uri.fromFile(fleIcon);
		}

		Log.v(TAG, "(II) Failed to locate icon, requesting from server: "
				+ fleIcon.getAbsolutePath());
		// 2. If cached icon does not exist, request icon from server
		// TODO: Run this as a Task!
		IconInfo icnIcon = m_actParent.getDisperServer().getIcon(p_sAppID);
		if (icnIcon != null) {
			fleIcon = saveIcon(icnIcon.getData(), icnIcon.getMD5());
			return Uri.fromFile(fleIcon);
		} else
			return null;
	}

	/**
	 * Parse applist and cache dir and remove any icons that does not appear to
	 * be used. I.e. any file that does not have a corresponing MD5-tag in the
	 * app list should go...
	 * 
	 * @param p_lstAvailableApps
	 */
	public void cleanCache(List<Application> p_lstAvailableApps) {
		throw new UnsupportedOperationException(
				"cleanCache() not yet implemented.");
	}
}
